//
//  RankingsViewController.m
//  CandyCrushClone
//
//  Created by Petar on 3/14/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "RankingsViewController.h"
#import "CommunicationManager.h"
#import "Globals.h"
#import "UIView+Animations.h"
#import "AudioController.h"
#import "Tracker.h"

static NSString * const RankingCellIdentifier = @"RankingCell";
static NSString * const LoadingCellIdentifier = @"LoadingCell";

@interface RankingsViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *localPlayerRatingLabel;
@property (weak, nonatomic) IBOutlet UILabel *localPlayerWinsLabel;
@property (weak, nonatomic) IBOutlet UILabel *localPlayerPlayedGamesLabel;
@property (weak, nonatomic) IBOutlet UILabel *localPlayerNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *backButton;

@end


@implementation RankingsViewController
{
    NSArray *_worldRankingResults;
    NSArray *_friendsRankingResults;
    BOOL _isWaitingForResponse;
    BOOL _shouldShowWorldRanking;
    NSDictionary *_localPlayerInfo;
    NSNumberFormatter *_decimalFormatter;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    _worldRankingResults = [NSArray new];
    _friendsRankingResults = [NSArray new];
    _isWaitingForResponse = YES;
    _shouldShowWorldRanking = YES;
    
    [_tableView setContentInset:UIEdgeInsetsMake(10, 0, 15, 0)];
    
    // getList with usernames from Server
    [[CommunicationManager sharedManager] getRankingLists];
    
    // Listen for UPDATE_LIST_OF_USERS from CommunicationManager
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateRankingsResults:)  name:UPDATE_RANKING_LISTS object:nil];
    
    [Tracker trackEvent:@"Seen Leaderboard" withParams:nil];
    
    _decimalFormatter = [NSNumberFormatter new];
    [_decimalFormatter setUsesGroupingSeparator:YES];
    [_decimalFormatter setGroupingSeparator:[[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    [_backButton startWobbleAnimationAfterDuration:0.25f];
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_backButton stopAllAnimations];
    
}


- (void)updateRankingsResults:(NSNotification *)notification
{
    
    // The searching is done.
    _isWaitingForResponse = NO;
    
    NSDictionary *userInfo = notification.userInfo;
    
    // Check for recieved worldRankingList
    NSMutableArray *worldRankingList = [NSMutableArray arrayWithArray:userInfo[WORLD_RANKING_LIST]];
    
    // LocalPlayerInfo is the first object in the Array
    _localPlayerInfo = [worldRankingList firstObject];
    [self updateLocalPlayerInfo];
    
    // Delete localPlayerInfo from array, so top25 PlayersInfo left in the array
    [worldRankingList removeObjectAtIndex:0];
    
    if ( worldRankingList != nil && [worldRankingList isKindOfClass:[NSArray class]] ) {
        _worldRankingResults = worldRankingList;
    }

//    // Check for recieved worldRankingList
//    NSArray *friendsRankingList = userInfo[FRIENDS_RANKING_LIST];
//    
//    if ( friendsRankingList != nil && [friendsRankingList isKindOfClass:[NSArray class]] ) {
//        _friendsRankingResults = friendsRankingList;
//    }
    
    // Refresh the TableView with RankingList
    [_tableView reloadData];
    
}


- (void)updateLocalPlayerInfo
{
    
    NSNumber *rankNumberValue = [_decimalFormatter numberFromString:_localPlayerInfo[RANK]];
    NSNumber *gamesNumberValue = [_decimalFormatter numberFromString:_localPlayerInfo[PLAYED_GAMES]];
    
    _localPlayerNameLabel.text = _localPlayerInfo[NAME];
    _localPlayerRatingLabel.text = [_decimalFormatter stringFromNumber:rankNumberValue];
    _localPlayerWinsLabel.text = [NSString stringWithFormat:@"%.2f%%",[_localPlayerInfo[WIN_PERCENTAGE] floatValue]];
    _localPlayerPlayedGamesLabel.text = [_decimalFormatter stringFromNumber:gamesNumberValue];
    
}


- (IBAction)didPressBackButton:(id)sender
{
    
    [[AudioController sharedInstance] playButtonClick];
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (IBAction)didPressWorldRankingButton:(id)sender
{
    
    _shouldShowWorldRanking = YES;
    [_tableView reloadData];
    
}


- (IBAction)didPressFriendsRankingButton:(id)sender
{
    
    _shouldShowWorldRanking = NO;
    [_tableView reloadData];
    
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Show LoadingCell if do NOT have response from the server yet
    if ( _isWaitingForResponse == YES ) {
        return 1; // Loading...
    }
    
    if ( _shouldShowWorldRanking == YES ) {
        return [_worldRankingResults count];
    } else {
        return [_friendsRankingResults count];
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ( _isWaitingForResponse == YES ) {
        
        // Show LoadingCell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LoadingCellIdentifier forIndexPath:indexPath];
        UIActivityIndicatorView *spinner = (UIActivityIndicatorView *)[cell viewWithTag:100];
        [spinner startAnimating];
        
        return cell;
        
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RankingCellIdentifier forIndexPath:indexPath];

    NSArray *dataSource;
    
    // Determine which RankingList should be shown
    if ( _shouldShowWorldRanking == YES ) {
        dataSource = _worldRankingResults;
    } else {
        dataSource = _friendsRankingResults;
    }
    
    NSDictionary *userInfo = dataSource[indexPath.row];
    NSNumber *rankNumberValue = [_decimalFormatter numberFromString:userInfo[RANK]];
    NSNumber *gamesNumberValue = [_decimalFormatter numberFromString:userInfo[PLAYED_GAMES]];
    
    // Set Buddy name as text in the label
    ((UILabel *)[_tableView viewWithTag:1]).text = [NSString stringWithFormat:@"%@", userInfo[NAME]];
    ((UILabel *)[_tableView viewWithTag:2]).text = [_decimalFormatter stringFromNumber:rankNumberValue];
    ((UILabel *)[_tableView viewWithTag:3]).text = [_decimalFormatter stringFromNumber:gamesNumberValue];
    ((UILabel *)[_tableView viewWithTag:4]).text = [NSString stringWithFormat:@"%.2f%%",[userInfo[WIN_PERCENTAGE] floatValue]];
    ((UILabel *)[_tableView viewWithTag:5]).text = [NSString stringWithFormat:@"%zd", indexPath.row + 1];
    
    return cell;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ( _isWaitingForResponse == YES ) {
        
        return 60; // Loading cell height
        
    } else {
        
        return 114; // PlayerInfo cell height
        
    }
    
}

-(BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
